import { stringify } from 'querystring';
import { history, Reducer, Effect } from 'umi';
import {  message } from 'antd';
import { fakeAccountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { _local } from '@/utils/localStorage';
import JwtDecode from 'jwt-decode';
export interface StateType {
  status?: 'ok' | 'error';
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
       _local.set('x-auth-token',response.token,1000*60*30)
       _local.set('user',JwtDecode(response.token),1000*60*30)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
            if (response.success === true) {
                message.success('登录成功！');
                const urlParams = new URL(window.location.href);
                const params = getPageQuery();
                let { redirect } = params as { redirect: string };
                if (redirect) {
                  const redirectUrlParams = new URL(redirect);
                  if (redirectUrlParams.origin === urlParams.origin) {
                    redirect = redirect.substr(urlParams.origin.length);
                  } else {
                    window.location.href = redirect;
                    return;
                  }
                }
                history.replace(redirect || '/');
              }else{
                message.error('用户名或密码错误！');
              }
      // if (response.success === true) {
      //       message.success('登录成功！');
      //       window.location.href = '/';
      //       return;
      //     }else{
      //       message.error('登录失败，请重试！');
      //     }
    },

   * logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      if (window.location.pathname !== '/user/login' && !redirect) {
       yield _local.remove('x-auth-token')
       yield _local.remove('user')
        history.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log(payload.status)
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};

export default Model;
